package com.lyy.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyy.Vo.UserEditVO;
import com.lyy.Vo.UserLogin;
import com.lyy.Vo.UserRole;
import com.lyy.Vo.UserVO;
import com.lyy.aspect.ControllerEndpoint;
import com.lyy.handler.BusinessException;
import com.lyy.response.Result;
import com.lyy.response.ResultCode;
import com.lyy.system.entity.RandomInfo;
import com.lyy.system.entity.User;
import com.lyy.system.entity.UserInfoVO;
import com.lyy.system.mapper.RandomInfoMapper;
import com.lyy.system.service.AliOssService;
import com.lyy.system.service.LoginLogService;
import com.lyy.system.service.UserService;
import com.lyy.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lyy
 * @since 2022-05-05
 */
@RestController
@RequestMapping("/user")
@Api(value = "系统用户模块",tags = "系统用户接口")
//@CrossOrigin  //解决跨域注解
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AliOssService aliOssService;

    @Autowired
    private RandomInfoMapper randomInfoMapper;

    @Autowired
    private LoginLogService loginLogService;

    @GetMapping("/queryAll")
    @ApiOperation(value = "用户列表",notes = "查询所有用户信息")
    public Result queryAll(){
        //int i=1/0;
        List<User> list =userService.list();
        return Result.ok().data("users",list);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个用户",notes = "通过id查询对应的用户信息")
    public Result getUserById(@PathVariable("id") Long id){
        User user =userService.getById(id);
        if (user!=null){
            return Result.ok().data("user",user);
        }else {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
    }

    /**
     * 分页查询用户列表
     * @return
     */
    @GetMapping("/findUserList")
    @ApiOperation(value = "分页查询用户列表",notes = "分页查询")
    public Result findUserList(@RequestParam(required = true,defaultValue = "1") Integer current,
                               @RequestParam(required = true,defaultValue = "6") Integer size){
        //对用户进行分页，泛型中注入的就是用户实体类
        Page<User> page = new Page<>(current,size);
        Page<User> userPage =userService.page(page);
        Long total= userPage.getTotal();
        List<User> records=userPage.getRecords();
        return  Result.ok().data("total",total).data("records",records);

    }

    /**
     * 条件分页查询
     * @param current
     * @param size
     * @param userVO
     * @return
     */
    @PostMapping("/findUserPage")
    @ApiOperation(value = "条件分页查询用户列表",notes = "条件分页查询")
    public Result findUserPage(@RequestParam(required = true,defaultValue = "1") Integer current,
                               @RequestParam(required = true,defaultValue = "6") Integer size,
                                @RequestBody UserVO userVO){
        //对用户进行分页，泛型中注入的就是实体类
        Page<User> page=new Page<>(current,size);
        //单表的时候其实这个方法非常好用
        QueryWrapper<User> wrapper=getWrapper(userVO);
        wrapper.eq("deleted",0);
        IPage<User> userIPage= userService.findUserPage(page,wrapper);
        Long total =userIPage.getTotal();
        List<User> records=userIPage.getRecords();
        return Result.ok().data("total",total).data("records",records);
    }

    /**
     *封装查询条件
     * @param userVO
     * @return
     */
    private QueryWrapper<User> getWrapper(UserVO userVO){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        if (userVO !=null){
            if (!StringUtils.isEmpty(userVO.getDepartmentId())){
                queryWrapper.eq("department_id",userVO.getDepartmentId());
            }
            if (!StringUtils.isEmpty(userVO.getUsername())){
                queryWrapper.eq("username",userVO.getUsername());
            }
            if (!StringUtils.isEmpty(userVO.getEmail())){
                queryWrapper.eq("email",userVO.getEmail());
            }
            if (!StringUtils.isEmpty(userVO.getSex())){
                queryWrapper.eq("sex",userVO.getSex());
            }
            if (!StringUtils.isEmpty(userVO.getNickname())){
                queryWrapper.eq("nickname",userVO.getNickname());
            }
        }
        return queryWrapper;
    }


    @ControllerEndpoint(exceptionMessage = "添加用户失败", operation = "添加用户")
    @ApiOperation(value = "添加用户",notes = "添加用户信息")
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user){
        userService.addUser(user);
        return Result.ok();

    }

    @ControllerEndpoint(exceptionMessage = "导出用户失败", operation = "导出用户")
    @ApiOperation(value = "导出用户信息")
    @PostMapping("/excel")
    public void exportUserExcel(HttpServletResponse response,@RequestBody(required = false) UserVO userVO) throws IOException{
        QueryWrapper<User> wrapper =getWrapper(userVO);
        wrapper.eq("deleted",0);
       // List<User> users=userService.list(wrapper);
        userService.exportUserExcel(response,wrapper);
    }

    @ApiOperation(value = "查询用户详情",notes = "用户详情")
    @PostMapping("/edit")
    public Result edit(Long id){
        UserEditVO userEditVO= userService.edit(id);
        return Result.ok().data("userEditVO",userEditVO);
    }

    @ControllerEndpoint(exceptionMessage = "更新用户失败", operation = "更新用户")
    @ApiOperation(value = "更新用户",notes = "更新用户信息")
    @PostMapping("/update")
    public Result update(@RequestBody UserEditVO userEditVO){
        userService.update(userEditVO);
        return Result.ok();
    }

    @ControllerEndpoint(exceptionMessage = "删除用户失败", operation = "删除用户")
    @ApiOperation(value = "删除用户",notes = "删除用户信息")
    @DeleteMapping("/delete")
    public Result delete(Long id){
        userService.deleteById(id);
        return Result.ok();
    }

    @ApiOperation(value = "用户登录" ,notes = "接收参数用户名和密码,并进行验证码检验，登入成功后,返回JWTToken")
    @PostMapping("/login")
    public Result login(@RequestBody UserLogin userLogin, HttpServletRequest request){
        QueryWrapper<RandomInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("dci_checkno",userLogin.getCheckNo());
        RandomInfo randomInfo=randomInfoMapper.selectOne(wrapper);
        if (randomInfo!=null){
            if (randomInfo.getDciCode().equals(userLogin.getCode())){
                RandomInfo randomInfo1=new RandomInfo();
                randomInfo1.setDciStt("1");
                randomInfo1.setDciVerifytime(new Date());
                String token = userService.login(userLogin);
                //更新检验码为已检验
                randomInfoMapper.update(randomInfo1,wrapper);
                UserInfoVO userInfoVO = userService.userInfo(userLogin.getUsername());
                loginLogService.add(request,token);
                return Result.ok().data("token",token).data("userInfoVO",userInfoVO);
            }else {
                throw new BusinessException(ResultCode.VERIFYCODE_ERROR.getCode(), ResultCode.VERIFYCODE_ERROR.getMessage());
            }

        }else {
            throw new BusinessException(ResultCode.VERIFYCODE_NOT_EXIST.getCode(),ResultCode.VERIFYCODE_NOT_EXIST.getMessage());
        }

    }

    @ControllerEndpoint(exceptionMessage = "用户授权失败", operation = "用户授权")
    @ApiOperation(value = "绑定用户角色" ,notes = "绑定用户角色")
    @PostMapping("/bindUserRole")
    public Result bindUserRole(@RequestBody UserRole userRole){
        userService.bindUserRole(userRole);
        return Result.ok();
    }

}

